package com.ld.project.zkn.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.TextConfigurationRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.ehcache.integrations.shiro.EhcacheShiroManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.Model;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm() {
        TextConfigurationRealm realm = new TextConfigurationRealm();
        realm.setUserDefinitions("joe.coder=password,user\n" +
                "jill.coder=password,admin");

        realm.setRoleDefinitions("admin=read,write\n" +
                "user=read");
        realm.setCachingEnabled(true);
        realm.setCredentialsMatcher(new HashedCredentialsMatcher());
        return realm;
    }
   @Bean
    public ModularRealmAuthenticator modularRealmAuthenticator(){
        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
       authenticator.setRealms(Arrays.asList(realm()));
        return authenticator;
    }
    @Bean
    public DefaultWebSecurityManager  securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager( new DefaultWebSessionManager());
        EhcacheShiroManager ehcacheShiroManager = new EhcacheShiroManager();
        ehcacheShiroManager.setCacheManagerConfigFile("classpath:ehcache.xml");
        securityManager.setCacheManager(ehcacheShiroManager);
        return securityManager;
    }
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean definition = new ShiroFilterFactoryBean();
        definition.setSecurityManager(securityManager());
        definition.setLoginUrl("/login");
        definition.setSuccessUrl("/index");
        Map<String, String> filterChainDefinition=new LinkedHashMap<>();
        filterChainDefinition.put("/**","authc");
        filterChainDefinition.put("/login","anon");
        definition.setFilterChainDefinitionMap(filterChainDefinition);
        return definition;
    }




}
